package com.lagou.springbootblog.service.impl;

import com.lagou.springbootblog.bean.PageParam;
import com.lagou.springbootblog.domain.Article;
import com.lagou.springbootblog.repository.ArticleRepository;
import com.lagou.springbootblog.service.ArticleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public List<Article> findAll() {
        return articleRepository.findAll();
    }

    @Override
    public Page<Article> getArticlesPage(PageParam pageParam, String keywords) {
        //规格定义
        Specification<Article> specification = new Specification<Article>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>(); //所有的断言
                if(StringUtils.isNotBlank(keywords)){ //添加断言
                    Predicate likeNickName = cb.like(root.get("title").as(String.class),keywords+"%");
                    predicates.add(likeNickName);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        //分页信息
        Pageable pageable = PageRequest.of(pageParam.getPage(), pageParam.getLimit(), Sort.by(Sort.Order.desc("created"))); //页码：前端从0开始，jpa从0开始，做个转换
        //分页查询
        return this.articleRepository.findAll(specification, pageable);
    }
}
